<?php

namespace app\index\controller;

use think\Controller;
use app\index\model\Book212006382;
use think\Db;
use think\View;

class Index extends Controller
{
    public function index()
    {
        $data = Book212006382::all();
        $this->view->assign('data', $data);
        $this->view->assign('number', count($data));
        return $this->view->fetch();
    }

    public function add()
    {
        return $this->view->fetch();
    }

    public function addbook()
    {
        $book = new Book212006382;
        $id = $book->max('id');
        $id++;
        $book->id = $id;
        $book->name = $_POST['name'];
        $book->category = $_POST['category'];
        $book->price = $_POST['price'];
        $book->publish_time = $_POST['publish_time'];
        $result = $book->save();
        if ($result) {
            echo "<script>alert('添加成功');window.location.href='index'</script>";
        } else {
            echo "<script>alert('添加失败');</script>";
        }
    }

    public function delete($id){
        $book = new Book212006382;
        $result = $book->get(['id'=>['=',$id]]);
        $result = $result->delete();
        if ($result) {
            echo "<script>alert('删除成功');window.location.href='index'</script>";
        } else {
            echo "<script>alert('删除失败');</script>";
        }
    }

    public function edit($id){
        $data = Db::name('book212006382')->where('id', $id)->find();
        $this->assign('data', $data);
        return $this->fetch();

    }

    public function updatebook(){
        $book = new Book212006382;
        $id= $_POST['id'];
        $name = $_POST['name'];
        $category = $_POST['category'];
        $price = $_POST['price'];
        $publish_time = $_POST['publish_time'];
        $where = ['id'=>$id];
        $data = ['price'=>$price,'name'=>$name,'category'=>$category,'publish_time'=>$publish_time];
        $result = $book->save($data,$where);
        if ($result) {
            echo "<script>alert('修改成功');window.location.href='index'</script>";
        } else {
            echo "<script>alert('修改失败');</script>";
        }
    }

}
